package com.richfit.barcodesystem_cczt.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;

/**
 * @author cl
 */
public class Update {
    private final Context mContext;

    public Update(Context context) {
        this.mContext = context;
    }

    /**
     * 获取本地APP版本号
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (Exception e) {

        }

        return versionCode;
    }

    /**
     * 获取版本号名称
     *
     * @param mcontext 上下文
     * @return
     */
    public static String getVerName(Context mcontext) {
        String verName = "";
        try {
            verName = mcontext.getPackageManager().
                    getPackageInfo(mcontext.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    /**
     * 判断版本号不一致，就更新。考虑到版本回退的情况
     *
     * @param version_service
     * @param mcontext
     * @return
     */
    public static boolean isNeedUpdate(String version_service, Context mcontext) {
        boolean isNeed = false;
        try {
            String version_current = getVerName(mcontext);//获取当前本地版本

            if (!TextUtils.isEmpty(version_service) && !TextUtils.isEmpty(version_current)) {
                if (!version_current.equals(version_service)) {
                    isNeed = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isNeed;
    }

    //下载apk
//    private void downloadAPK(String url, String name) {
//        //创建下载任务
//        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//        //移动网络情况下是否允许漫游
//        request.setAllowedOverRoaming(false);
//        //在通知栏中显示，默认就是显示的
//        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
//        request.setTitle("通知标题，随意修改");
//        request.setDescription("新版***下载中...");
//        request.setVisibleInDownloadsUi(true);
//
//        //设置下载的路径
//        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name);
//        request.setDestinationUri(Uri.fromFile(file));
//        pathstr = file.getAbsolutePath();
//        //获取DownloadManager
//        if (downloadManager == null)
//            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
//        //将下载请求加入下载队列，加入下载队列后会给该任务返回一个long型的id，通过该id可以取消任务，重启任务、获取下载的文件等等
//        if (downloadManager != null) {
//            downloadId = downloadManager.enqueue(request);
//        }
//
//        //注册广播接收者，监听下载状态
//        mContext.registerReceiver(receiver,
//                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//    }

}
